<?php
namespace app\shop\controller;
use think\Input;
class Api extends Common{
    public function initialize(){
        parent::initialize();
        header('Access-Control-Allow-Origin:*');
    }
    // 商城码商通道列表
    public function channels(){  
        if(request()->isGet()){
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):15; 
            $shopid =input('shopid')?input('shopid'):0; 
            $appid =input('appid')?input('appid'):0; 
            if($shopid){
	            $list=db('channel')->where('shopid',$shopid)->where('shopappid',$appid)->where('open',1)
	            	->field('id as channelid,shopid,shopname,cionname,title,price')
	                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
	                ->toArray();
	            if($list['total']!==0){
            		$result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
            	}else{
            		$result = ['code'=>-1,'msg'=>'暂未开放!'];
            	}
            }else{
            	$result = ['code'=>-1,'msg'=>'没有找到!'];
            }
            return json($result);
        }
    } 
    // 单个码商通道信息
    public function channelinfo($shopid='',$appid='',$channelid=''){  
        if(request()->isGet()){  
            if($shopid){ 
	            $info=db('channel')->where('shopid',$shopid)->where('shopappid',$appid)->where('id',$channelid)->where('open',1)
	            	->field('id as channelid,shopid,shopname,cionname,title,price,userid as uuid')->find();  
	            $payinfo=db('user_banks')->where('userid',$info['uuid'])->where('open',1)
	            	->field('name,id as bankid,bank_name')->select();  
	            foreach ($payinfo as $k=>$v){
	                $payinfo[$k]['name'] = $v['name'].'('.$v['bank_name'].')';
	            }
            	if($info){
            		$result = ['code'=>0,'msg'=>'获取成功!','info'=>$info,'payinfo'=>$payinfo]; 
            	}else{
            		$result = ['code'=>-1,'msg'=>'没有找到!'];
            	}
            }else{
            	$result = ['code'=>-1,'msg'=>'没有找到!'];
            }
            return json($result);
        }
    } 
    // 接收订单
    public function makeorder($channelid='',$number='',$shopid='',$appid='',$orderid='',$paytype='',$note=''){ 
    	if(request()->isPost()){ 
    		$info=db('channel')->where('id',$channelid)->where('shopid',$shopid)->where('shopappid',$appid)->where('open',1)->find();
    		if($info){
    			$orderidnew=$channelid.'N'.rand_string(8,1).'S'.$shopid;
    			$data['orderid']=$orderidnew; 
    			$data['orderid_out']=$orderid?$orderid:date("YmdHis",time());
    			$data['channelname']=$info['title'];
    			$data['channelid']=$info['id'];
    			$data['shopname']=$info['shopname'];
    			$data['shopid']=$info['shopid'];
    			$data['cionname']=$info['cionname'];
    			$data['cionid']=$info['cionid'];
    			$data['shopappid']=$info['shopappid'];
                $data['userid']=$info['userid'];
                $data['agentid']=$info['agentid'];
    			$data['price']=$info['price']; 
    			$data['number']=string2array($number);
    			$data['money']=$data['number']*$data['price']; 
    			$data['addtime']=time(); 
    			$data['bankid']=$paytype;
    			$data['state']=0;
    			$data['note']=$note;
    			// 手续费
    			$data['fei_user']=$info['rate']*$data['money']*0.01;
    			$data['fei_user_lv']=$info['rate']; 
                $shopinfo=db('shop')->where('id',$info['shopid'])->find();
                $data['fei_shop']=$shopinfo['lv']*$data['money']*0.01;
                $data['fei_shop_lv']=$shopinfo['lv'];
                if($info['agentid']){
                    $agentinfo=db('users')->where('id',$info['agentid'])->find();
                    $data['fei_agent']=$agentinfo['agentlv']*$data['money']*0.01;
                    $data['fei_agent_lv']=$agentinfo['agentlv'];  
                }
    			$id = db('channel_order')->insertGetId($data);
    			if($id){ 
    				$payurl=url('shop/api/pay',['orderid'=>$orderidnew,'appid'=>$appid]);
    				$result = ['code'=>0,'msg'=>'跳转支付……','orderid'=>$orderidnew,'payurl'=>$payurl];
    			}else{
    				$result = ['code'=>-1,'msg'=>'提交失败，请重试!'];
    			} 
    		}else{
    			$result = ['code'=>-1,'msg'=>'通道异常!'];
    		}
    	}
    	return json($result);
    }
    // 去支付
    public function pay($orderid='',$appid=''){ 
        if(request()->isPost()){ 
            $order=db('channel_order')->where('orderid',$orderid)->where('shopappid',$appid)->find();
            if($order['state']===0){
                if(db('channel_order')->where('orderid',$orderid)->where('shopappid',$appid)->update(['state'=>1,'paytime'=>time()])!==false){
                    db('channel')->where('id',$order['channelid'])->where('shopappid',$order['shopappid'])->setInc('money_total',$order['money']);    
                    $result = ['code'=>1,'msg'=>'支付成功……','callbackurl'=>url('shop/api/pay',['orderid'=>$orderid,'appid'=>$appid]),'orderid'=>$order['orderid']];   
                }else{
                    $result = ['code'=>-1,'msg'=>'系统繁忙，请稍后再试!','orderid'=>$order['orderid']];
                }
            }else{
                $result = ['code'=>-1,'msg'=>'该订单已经支付或取消!','orderid'=>$order['orderid']];
            } 
            if($result['code']===1){
                $this->emailnotice($order['userid'],$order['orderid'],$order['shopname'],$order['cionname'],$order['number'],$order['money']); 
            }
            return $result;
        }else{
            $order=db('channel_order')->alias('o')
                ->join(config('database.prefix') . 'user_banks ub', 'o.bankid = ub.id', 'left')
                ->field('o.*,ub.name,ub.bank_name,ub.name_en,ub.qrcode,ub.bank_no,ub.content')
                ->where('o.orderid',$orderid)->where('o.shopappid',$appid)->find(); 
            if($order['state']===0){
                $this->assign('order',$order); 
                return $this->fetch('index/pay');
            }else if($order['state']===1){
                $result = ['code'=>1,'msg'=>'已支付待确认!','orderid'=>$order['orderid']];
            }else if($order['state']===2){
                $result = ['code'=>2,'msg'=>'该订单支付完成!','orderid'=>$order['orderid']];
            }else{
                $result = ['code'=>-1,'msg'=>'该订单已经支付或取消!','orderid'=>$order['orderid']];
            }   
            return json($result);
        }      
    }
    // 邮件通知
    public function emailnotice($userid='',$orderid='',$shopname='',$cionname='',$number='',$money=''){ 
        $sender=db('users')->where('id',$userid)->value('email');
        $content='<div  style="width: 600px; margin:10px auto; border:5px solid #ff9422; padding: 38px;">订单编号：'.$orderid.'<br/>订单金额：'.$money.'元<br/>来自商城：'.$shopname.'<br/>购买产品：'.$cionname.'<br/>购买数量：'.$number.'<br/><hr><br/><b>提醒：为能正常收到通知邮件，请将本邮箱添加至白名单。</b><br/>如您已收到相应的款项，请点击下方链接，对订单进行处理<br/>点击进入：<a href="'.$this->sys['url'].'" target="_blank">'.$this->sys['url'].'</a></div>';
        $send = send_email($sender, '新订单提醒【'.$orderid.'】', $content);
    }
} 